package com.smg.community.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;



public class FileUtil {
	/**
	* 删除单个文件
	* @param   fileName    被删除文件的文件名
	* @return 单个文件删除成功返回true,否则返回false
	**/
	public static boolean deleteFile(String fileName){
		File file = new File(fileName);
		if(file.isFile() && file.exists()){
			file.delete();
			System.out.println("删除单个文件" + fileName + "成功！");
			return true;
		}else{
			System.out.println("删除单个文件" + fileName + "失败！");
			return false;
		}
	}
	/**
	 * 加载属性文件
	 * 
	 * @param filePath
	 *            文件路径
	 * @return 属性文件
	 */
	public static Properties loadProperties(String filePath)
	{
		Properties p = new Properties();
		try
		{
			String suffix = ".properties";
			if (filePath.lastIndexOf(suffix) == -1)
			{
				filePath += suffix;
			}
			p.load(FileUtil.getFileInputStream(filePath));
		} catch (Exception e)
		{
		}
		return p;
	}

	/**
	 * 根据文件路径获取输入流
	 * 
	 * @param filePath
	 *            文件路径
	 * @return 输入流
	 */
	public static InputStream getFileInputStream(String filePath)
	{
		InputStream fis = null;
		try
		{
			fis = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
		} catch (Exception e)
		{
		}
		return fis;
	}
	
	/**    
     * 删除文件，可以是单个文件或文件夹
     * @param   fileName    待删除的文件名
     * @return 文件删除成功返回true,否则返回false
     */     
    public static boolean delete(String fileName){
        File file = new File(fileName);
        if(!file.exists()){
            System.out.println("删除文件失败："+fileName+"文件不存在");
            return false;
        }else{
            if(file.isFile()){
                return deleteFile(fileName);
            }else{
                return deleteDirectory(fileName,true);
            }
        }
    }

    public static void main(String[] args){
    	
    	SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		Date dt = new Date(System.currentTimeMillis());

		String filename = fmt.format(dt);
    	System.out.println(filename);
//    	String dir = "D:\\Workspaces\\eclipse 3.7\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp3\\wtpwebapps\\ddmap-web-weicheng\\upload";
//    	//FileUtil.deleteDirectory(dir,false);
//    	List<String> list = FileUtil.getFileNames(dir, "");
//    	for (String s : list) {
//			System.out.println(s);
//		}	
//    	System.out.println(Pattern.compile("\\w*.txt\\z").matcher("asas.txttxt").find());
//    	/*if(!dir.endsWith(File.separator)){
//            dir = dir + File.separator;
//        }
//    	File dirFile = new File(dir);
//    	System.out.println(dirFile.delete() ? "删除成功！" : "删除失败！");*/
    }
    /**
     * 删除目录（文件夹）以及目录下的文件
     * @param   dir 被删除目录的文件路径
     * @param   isDeleteDir 是否删除目录
     * @return  目录删除成功返回true,否则返回false
     */
    public static boolean deleteDirectory(String dir,boolean isDeleteDir){
    	
    	//如果dir不以文件分隔符结尾，自动添加文件分隔符
    	if(!dir.endsWith(File.separator)){
    		dir = dir + File.separator;
    	}
    	File dirFile = new File(dir);
    	//如果dir对应的文件不存在，或者不是一个目录，则退出
    	if(!dirFile.exists() || !dirFile.isDirectory()){
    		System.out.println("删除目录失败，" + dir + "目录不存在！");
    		return false;
    	}
    	boolean flag = true;
    	//删除文件夹下的所有文件(包括子目录)
    	File[] files = dirFile.listFiles();
    	for(int i=0;i<files.length;i++){
    		//删除子文件
    		if(files[i].isFile()){
    			flag = deleteFile(files[i].getAbsolutePath());
    			if(!flag) break;
    		}else{
    			//删除子目录
    			flag = deleteDirectory(files[i].getAbsolutePath(),true);
    			if(!flag) break;
    		}
    	}
    	if(!flag){
    		System.out.println("删除目录下文件失败！");
    		return false;
    	}
    	//删除当前目录
    	if(isDeleteDir){
    		dirFile.delete();
    	}
    	return true;
    }
    
    /**
     * 获取目录下指定后缀名的文件列表名称
     * @param path 文件存放路径
     * @param regex 要查找的文件后缀名(如不填则查找所有文件)
     * */
  	public static List<String> getFileNames(String path,String regex) {
        File file = new File(path);
        if (!file.exists()){
        	System.out.println(path + " not exists");
            return null;
        }
        File[] array = file.listFiles();
        List<String> list = new ArrayList<String>();
        for(File f : array){
        	if(f.isFile() && Pattern.compile("\\w*" + regex + "\\z").matcher(f.getName()).find()){
        		list.add(f.getName());
            }else if(f.isDirectory()){
            	getFileNames(f.getPath(),regex);
            }
        }
        return list;
  	}
  	/**
  	 * 读取文件内容(按行读取)
  	 * @param txtPath 被读取文件存放路径
  	 * @param set 保存被读取的文件内容集合
  	 * */
  	public static void readFile(String txtPath,Collection<Object> collection) {
		//HashSet<String> set = new HashSet<String>();
		File file = new File(txtPath);
		if(!file.exists()){
			System.out.println(txtPath + " not exists");
			return;
		}
		String text;
		try {
			//FileInputStream fr = new FileInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));
			while((text = br.readLine()) != null){
				if(text.equals("")){
					continue;
				}
				collection.add(text);
			}
			br.close();
			//fr.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		//return set;
	}
  	/**
  	 * 读取并过滤重复文件内容(按行读取)
  	 * @param txtPath 被读取文件存放路径
  	 * @param set 保存被读取的文件内容集合
  	 * */
  	public static void readFileUnRepeat(String txtPath,Collection<Object> collection) {
  		//HashSet<String> set = new HashSet<String>();
  		File file = new File(txtPath);
  		if(!file.exists()){
			System.out.println(txtPath + " not exists");
			return;
		}
  		String text;
  		try {
  			//FileInputStream fr = new FileInputStream(file);
  			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));
  			while((text = br.readLine()) != null){
  				if(text.equals("") || collection.contains(text)){
  					continue;
  				}
  				collection.add(text);
  			}
  			br.close();
  			//fr.close();
  		} catch (Exception ex) {
  			ex.printStackTrace();
  		}
  		//return set;
  	}
  	public static void write(String fileName,String cont) {
//		FileWriter fw = new FileWriter(fileName);
		//String s = "hello world";
//		fw.write(cont,0,cont.length());
//		fw.flush();
//		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("hello2.txt"));
//		osw.write(cont,0,cont.length());
//		osw.flush();
		PrintWriter pw = null;
		try {
			pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileName)),true);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally{
			pw.println(cont);
			pw.flush();
		}
	}
  	/**
	 * 上传文件方法
	 * @param multipartRequest spring上传专用请求域
	 * @param uploadPath 上传文件存放路径
	 * @param fileName 上传文件名称(如果为 null，则直接取文件原名称)
	 * @param uploadFileName 页面中file表单元素名称
	 * @return 文件上传成功后所在路径（如为null 则表示没有上传文件）
	 * @throws IOException 
	 * */
  	public static String uploads(MultipartHttpServletRequest multipartRequest,String uploadPath,String fileName,String uploadFileName){
  		File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        String path = null;
  		CommonsMultipartFile  orginalFile = (CommonsMultipartFile) multipartRequest.getFile(uploadFileName);
  		DiskFileItemFactory factory = new DiskFileItemFactory();
  		//设置最多只允许在内存中存储的数据,单位:字节
  		//factory.setSizeThreshold((int)orginalFile.getSize());
  		//设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
  		//factory.setRepository(new File(uploadPath));
  		//ServletFileUpload upload = new ServletFileUpload(factory);
  		//upload.setHeaderEncoding("utf-8");

  		try {
			if(orginalFile != null && !orginalFile.isEmpty()){
				FileItem fileItem = orginalFile.getFileItem();
	  			int i = fileItem.getName().lastIndexOf("/");
	  			if(fileName == null){
		  			fileName = i > 0 ? fileItem.getName().substring(i) : fileItem.getName();
		  			//fileName = orginalFile.getOriginalFilename();同上面的方法作用都一样
		  			fileName = new String(fileName.getBytes("GBK"),"UTF-8");
	  			}else{
	  				//为文件名加后缀名
	  				fileName += fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
	  			}
	  			path = uploadPath + "/" + fileName;
				fileItem.write(new File(uploadPath,fileName));
				/*String ext = myFile.getFileExt(); // 取得后缀名
				SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
				Date dt = new Date(System.currentTimeMillis());

				String filename = fmt.format(dt);
				saveurl = request.getRealPath("\\")+"file\\";
				saveurl += filename + "." + ext;// 最终文件的保存路径
				String name = filename + "." + ext; */
			}
  		}  catch (Exception e){
  			e.printStackTrace();
  		}
  		return path;
  	}
  	/**
	 * 上传文件方法（只支持spring）
	 * @param uploadPath 上传文件存放路径
	 * @param fileName 页面中file表单元素名称
	 * @return 文件上传成功后所在路径
	 * @throws IOException 
	 * */
	public static String upload(MultipartHttpServletRequest multipartRequest,String uploadPath,String fileName) throws IOException{
		File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        String path = null;
        DataOutputStream out = null;
        InputStream is = null;//附件输入流
		try {
			CommonsMultipartFile  orginalFile = (CommonsMultipartFile) multipartRequest.getFile(fileName);
			if(orginalFile != null && !orginalFile.isEmpty()){
				//不同浏览器获取的结果可能会不一样,导致的结果是,传上来的文件路径可能是全路径(如 C:\Documents and Settings\Administrator\桌面\cc.txt),
				//也有可能只是文件的名称(如 cc.txt),所以这里要加以判断!  System.out.println("s:::"+s);
				String s = orginalFile.getFileItem().getName();
				s = s.lastIndexOf("\\") > 0 ? s.substring(s.lastIndexOf("\\")) : "\\" + s;
				path = uploadPath + s;
				out = new DataOutputStream(new FileOutputStream(uploadPath + s));//存放文件的绝对路径
				is = orginalFile.getInputStream();
				//定义一个字节数组做缓冲区，大小是源文件大小
				byte[] buffer = new byte[(int)orginalFile.getSize()];
				while(is.read(buffer) > 0) {
					out.write(buffer);//   写入磁盘；
				}
			}
	    } catch (Exception e) {
	    	e.printStackTrace();
	    } finally {
	    	if (is != null)is.close();
	   		if (out != null)out.close();
	    }
		return path;
	}
}
